#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8080

void handle_client(int client_fd) {
    char buffer[1024];
    
    while (1) {
        int len = recv(client_fd, buffer, sizeof(buffer), 0);
        if (len <= 0) break;
        
        buffer[len] = '\0';
        
        if (strcmp(buffer, "HEARTBEAT") == 0) {
            send(client_fd, "HEARTBEAT_ACK", 13, 0);
        } else {
            printf("client message is received: %s\n", buffer);
            send(client_fd, buffer, len, 0); // 回显
        }
    }
    
    close(client_fd);
}

int main() {
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(PORT),
        .sin_addr.s_addr = INADDR_ANY
    };

    bind(server_fd, (struct sockaddr*)&addr, sizeof(addr));
    listen(server_fd, 5);
    printf("The server is up, listening on the port %d\n", PORT);

    while (1) {
        int client_fd = accept(server_fd, NULL, NULL);
        printf("New client connections\n");
        handle_client(client_fd);
        printf("The client disconnects\n");
    }

    return 0;
}